package com.sgg.datastructure.huffmancode;

import java.util.*;

public class HuffmanCode {
    public static void main(String[] args) {
        String str = "i like like like java do you like a java";
        byte[] bytes = str.getBytes();
        System.out.println(bytes.length);
        List<Node> nodes = getNodes(bytes);
        System.out.println(nodes);
        Node huffmanTree = createHuffmanTree(nodes);
//        huffmanTree.preOrderPrint();
        Map<Byte, String> codeTable = createCodeTable(huffmanTree);
//        System.out.println(codeTable);
        byte[] compress = compress(bytes, codeTable);
//        byte[] result = huffmanZip(bytes);
//
//        System.out.println(Arrays.toString(result));
//        System.out.println(result.length);
//
//        System.out.println(Arrays.toString(huffmanUnzip(createCodeTable(createHuffmanTree(getNodes(bytes))), bytes)));

    }

    //利用map 创建list
    public static List<Node> getNodes(byte[] bytes) {
        List<Node> list = new ArrayList<>();
        Map<Byte, Integer> map = new HashMap<>();
        for (byte b : bytes) {
            map.merge(b, 1, Integer::sum);
        }
        for (Map.Entry<Byte, Integer> e : map.entrySet()) {
            list.add(new Node(e.getKey(), e.getValue()));
        }
        return list;
    }

    //list构建霍夫曼树
    public static Node createHuffmanTree(List<Node> list) {
        while (list.size() > 1) {
            Collections.sort(list);
            Node left = list.get(0);
            Node right = list.get(1);
            Node parent = new Node(null, left.weight + right.weight);//非叶子节点不用存放数据data
            parent.left = left;
            parent.right = right;
            list.remove(left);
            list.remove(right);
            list.add(parent);
        }
        return list.get(0);
    }

    public static StringBuilder sb = new StringBuilder();
    public static Map<Byte, String> codeTable = new HashMap<>();

    //生成霍夫曼树的编码表，重载
    public static Map<Byte, String> createCodeTable(Node node) {
        createCodeTable(node.left, "0", sb);
        createCodeTable(node.right, "1", sb);
        return codeTable;
    }

    //递归 生成霍夫曼树的编码表
    public static void createCodeTable(Node node, String code, StringBuilder fullCode) {
        StringBuilder result = new StringBuilder(fullCode);
        result.append(code);
        if (node != null) {
            if (node.data == null) {
                createCodeTable(node.left, "0", result);
                createCodeTable(node.right, "1", result);
            } else {
                codeTable.put(node.data, result.toString());
            }
        }
    }

    //压缩
    public static byte[] compress(byte[] bytes, Map<Byte, String> codeTable) {
        StringBuilder sb = new StringBuilder();
        for (byte bb : bytes) {
            sb.append(codeTable.get(bb));
        }//133
        //转byte
        int len;
        if (sb.length() % 8 == 0) {
            len = sb.length() / 8;
        } else {
            len = sb.length() / 8 + 1;
        }
        byte[] result = new byte[len];
        int index = 0;
        for (int i = 0; i < sb.length(); i = i + 8) {
            String str;
            if (i + 8 > sb.length()) {
                str = sb.substring(i);
            } else {
                str = sb.substring(i, i + 8);
            }
            result[index++] = (byte) Integer.parseInt(str, 2);
        }
        return result;
    }

    //封装压缩方法
    public static byte[] huffmanZip(byte[] bytes) {
        List<Node> nodes = getNodes(bytes);
        Node huffmanTree = createHuffmanTree(nodes);
        Map<Byte, String> codeTable = createCodeTable(huffmanTree);
        return compress(bytes, codeTable);
    }

    //解压
    public static byte[] huffmanUnzip(Map<Byte, String> codeTable, byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            boolean flag = (i == bytes.length - 1);
            stringBuilder.append(byteToBitString(!flag, b));
        }

        Map<String, Byte> map = new HashMap<String, Byte>();
        for (Map.Entry<Byte, String> entry : codeTable.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder.length(); ) {
            int count = 1; // 小的计数器
            boolean flag = true;
            Byte b = null;
            while (flag) {
                String key = stringBuilder.substring(i, i + count);//i 不动，让 count 移动，指定匹配到一个字符
                b = map.get(key);
                if (b == null) {//说明没有匹配到
                    count++;
                } else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;//i 直接移动到 count
        }
        byte b[] = new byte[list.size()];
        for (int i = 0; i < b.length; i++) {
            b[i] = list.get(i);
        }
        return b;
    }

    private static String byteToBitString(boolean flag, byte b) {
        int temp = b;
        if (flag) {
            temp |= 256; //按位与 256 1 0000 0000 | 0000 0001 => 1 0000 0001
        }
        String str = Integer.toBinaryString(temp); //返回的是 temp 对应的二进制的补码
        if (flag) {
            return str.substring(str.length() - 8);
        } else {
            return str;
        }
    }


}
